<template>
  <div class="websocket-container">
    <h1>WebSocket 连接</h1>
    <div class="connection-status">
      状态: {{ connectionStatus }}
    </div>
    <div class="input-area">
      <input v-model="userInput" @keyup.enter="sendMessage" placeholder="输入消息..." />
      <button @click="sendMessage">发送</button>
    </div>
    <div class="output-area">
      <div v-if="messages.length === 0" class="no-messages">暂无消息</div>
      <div v-else class="message-list">
        <div v-for="(message, index) in messages" :key="index" class="message">
          <div class="message-type">{{ message.type }}</div>
          <div class="message-content">{{ message.content }}</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'WebSocketView',
  data() {
    return {
      socket: null,
      connectionStatus: '未连接',
      userInput: '',
      messages: [],
      streamingMessage: '',
      reconnectAttempts: 0,
      maxReconnectAttempts: 5
    }
  },
  mounted() {
    this.connectWebSocket()
  },
  beforeUnmount() {
    if (this.socket) {
      this.socket.close()
    }
  },
  methods: {
    connectWebSocket() {
      // 关闭之前的连接（如果存在）
      if (this.socket) {
        this.socket.close()
      }
      
      this.connectionStatus = '正在连接'
      console.log('正在连接WebSocket...')
      
      // 使用try-catch包装WebSocket创建
      try {
        // 确保使用正确的WebSocket URL
        this.socket = new WebSocket('ws://localhost:8000/ws')
        
        this.socket.onopen = () => {
          console.log('WebSocket连接已建立')
          this.connectionStatus = '已连接'
          this.reconnectAttempts = 0 // 重置重连计数
          this.messages.push({
            type: '系统',
            content: '连接已建立'
          })
        }
        
        this.socket.onmessage = (event) => {
          console.log('收到WebSocket消息:', event.data)
          // 处理流式返回的数据
          const data = event.data
          if (data === '[END]') {
            // 流式消息结束标记
            this.messages.push({
              type: '接收',
              content: this.streamingMessage
            })
            this.streamingMessage = ''
          } else {
            // 累积流式消息
            this.streamingMessage += data
            // 更新最后一条消息以显示流式效果
            if (this.messages.length > 0 && this.messages[this.messages.length - 1].type === '流式') {
              this.messages[this.messages.length - 1].content = this.streamingMessage
            } else {
              this.messages.push({
                type: '流式',
                content: this.streamingMessage
              })
            }
          }
        }
        
        this.socket.onclose = (event) => {
          console.log('WebSocket连接已关闭:', event)
          this.connectionStatus = '已断开'
          this.messages.push({
            type: '系统',
            content: `连接已关闭 (代码: ${event.code})`
          })
          
          // 尝试重新连接
          if (this.reconnectAttempts < this.maxReconnectAttempts) {
            this.reconnectAttempts++
            const delay = Math.min(1000 * Math.pow(2, this.reconnectAttempts), 10000)
            console.log(`尝试在 ${delay}ms 后重新连接 (尝试 ${this.reconnectAttempts}/${this.maxReconnectAttempts})`)
            setTimeout(() => this.connectWebSocket(), delay)
          }
        }
        
        this.socket.onerror = (error) => {
          console.error('WebSocket错误:', error)
          this.connectionStatus = '错误'
          this.messages.push({
            type: '错误',
            content: '连接发生错误'
          })
        }
      } catch (error) {
        console.error('创建WebSocket连接时出错:', error)
        this.connectionStatus = '错误'
        this.messages.push({
          type: '错误',
          content: `创建连接失败: ${error.message}`
        })
      }
    },
    
    sendMessage() {
      if (!this.userInput.trim()) {
        return
      }
      
      if (!this.socket || this.socket.readyState !== WebSocket.OPEN) {
        console.error('WebSocket未连接，无法发送消息')
        this.messages.push({
          type: '错误',
          content: 'WebSocket未连接，无法发送消息'
        })
        return
      }
      
      console.log('发送WebSocket消息:', this.userInput)
      this.socket.send(this.userInput)
      this.messages.push({
        type: '发送',
        content: this.userInput
      })
      this.userInput = ''
    }
  }
}
</script>

<style scoped>
/* 样式保持不变 */
.websocket-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.connection-status {
  margin-bottom: 20px;
  padding: 10px;
  background-color: #f5f5f5;
  border-radius: 4px;
}

.input-area {
  display: flex;
  margin-bottom: 20px;
}

.input-area input {
  flex: 1;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px 0 0 4px;
}

.input-area button {
  padding: 8px 16px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 0 4px 4px 0;
  cursor: pointer;
}

.output-area {
  border: 1px solid #ddd;
  border-radius: 4px;
  height: 400px;
  overflow-y: auto;
  padding: 10px;
}

.no-messages {
  color: #999;
  text-align: center;
  margin-top: 180px;
}

.message {
  margin-bottom: 10px;
  padding: 10px;
  border-radius: 4px;
  background-color: #f9f9f9;
}

.message-type {
  font-weight: bold;
  margin-bottom: 5px;
}

.message-content {
  white-space: pre-wrap;
  word-break: break-word;
}
</style>